import http from './http'
import FormData from 'form-data'
import Result from '../utils/entity/Result'

const csrfTokenURL = '/' // csrf token 初始化
const uploadTempImageURL = '/upload/temp/image' // 上传图片到临时目录，单个上传；上传后的图片会等比缩放和裁剪
const uploadTempURL = '/upload/temp' // 上传到临时目录，单个上传
const uploadTempsURL = '/upload/temps' // 上传到临时目录，批量上传
const uploadUserAvatarURL = '/upload/user/avatar' // 上传用户头像

/**
 * 后台服务请求：通用模块
 * @author 谢长春 2020-03-10
 */
export default class UploadService {
  /**
   * 初始化 csrf token
   * @return {Promise<String>}
   */
  static async csrfToken() {
    return await http
      .head(csrfTokenURL)
      .then(res => {
        if (process.env.NODE_ENV === 'development') {
          console.log(res.headers['set-cookie'])
        }
        if (res.status >= 200 && res.status < 300) {
          return 'ok'
        } else {
          return 'fail'
        }
      })
      .catch(() => 'error')
  }

  /**
   * 上传图片到临时目录，单个上传；上传后的图片会等比缩放和裁剪
   * @param file {File|ReadStream} 单个文件
   * @return {Promise<Result>}
   */
  static async uploadTempImage(file) {
    const form = new FormData()
    form.append('file', file)
    const headers = form.getHeaders ? form.getHeaders() : {}
    return await http
      .post(uploadTempImageURL, form, {headers})
      .then(Result.ofResponse)
      .catch(Result.ofCatch)
  }

  /**
   * 上传到临时目录，单个上传
   * @param file {File|ReadStream} 单个文件
   * @return {Promise<Result>}
   */
  static async uploadTemp(file) {
    const form = new FormData()
    form.append('file', file)
    const headers = form.getHeaders ? form.getHeaders() : {}
    return await http
      .post(uploadTempURL, form, {headers})
      .then(Result.ofResponse)
      .catch(Result.ofCatch)
  }

  /**
   * 上传到临时目录，批量上传
   * @param files {File[]} 文件数组
   * @return {Promise<Result>}
   */
  static async uploadTemps(files) {
    const form = new FormData()
    files.forEach(file => {
      form.append('files', file)
    })
    const headers = form.getHeaders ? form.getHeaders() : {}
    return await http
      .post(uploadTempsURL, form, {headers})
      .then(Result.ofResponse)
      .catch(Result.ofCatch)
  }

  /**
   * 上传用户头像
   * @param file {File} 单个文件
   * @return {Promise<Result>}
   */
  static async uploadUserAvatar(file) {
    const form = new FormData()
    form.append('file', file)
    const headers = form.getHeaders ? form.getHeaders() : {}
    return await http
      .post(uploadUserAvatarURL, form, {headers})
      .then(Result.ofResponse)
      .catch(Result.ofCatch)
  }
}
